package com.hc.plugintower.net

import com.hcc.plugindust.data.datastore.UserInfoDataStoreKey
import com.yc.jetpacklib.data.datastore.YcDataStore
import com.yc.jetpacklib.extension.ycIsNotEmpty
import com.yc.jetpacklib.extension.ycLogESimple

import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * 劳务接口cookie值必须持久化。。。。。
 */
class CookieIntercept : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var originReq = chain.request()
        val builder = originReq.newBuilder().apply {

            if (!chain.request().url.toString().contains("dmsApi/auth")) {
                removeHeader("User-Agent") //移除旧的
                addHeader("User-Agent", "android")

                ycLogESimple("开始读取本地token")
                runBlocking {
                    YcDataStore.get(UserInfoDataStoreKey.KEY_USER_TOKEN) {
                        ycLogESimple("本地token:$it")
                        it?.apply {
                            addHeader("Authorization", "$it")
                        }
                    }
                }
                ycLogESimple("结束读取本地token")
            }
        }.build()
        return chain.proceed(builder)

    }
}